const app = getApp();
const my = require('../../classes/lib/util.js');
const user = require('../../classes/application/user.js');
const address = require('../../classes/application/address.js');
Page({

  data: {
    themes: null,
    regionData: [],
    regionIndex: [],
    maxDataType:3,
    formReady:false,
  },

  onLoad: function (options) {
    this.setData({
      themes: app.globalData.themes
    })    
    this.loadRegion(1,1);
  },
  loadRegion: function (dataType, parentKey) {
    var that = this;
    address.region({
      "type": dataType,
      parent: parentKey,
      callback: function (data) {
        var region = that.data.regionData;
        var idx = that.data.regionIndex;
        console.log("region:loadRegion:dataType=" + dataType);
        region[dataType] = data;
        idx[dataType] = 0;
        console.log("region:loadRegion:data size=" + data.length);
        that.setData({
          regionData: region,
          regionIndex: idx,
        });
        if (dataType < that.data.maxDataType) {
          that.loadRegion(dataType + 1, data[0].region_id);
        } else {
          that.setData({
            formReady: true,
          });
        }
      }
    })
  },
  doSelectRegion: function (e) {
    this.setData({
      formReady: false,
    })
    var _type = my.ival(e.currentTarget.dataset.type);
    console.log("region:doSelectRegion:_type="+_type);
    var _idx = e.detail.value;
    console.log("region:doSelectRegion:_idx=" + _idx);
    var region = this.data.regionData[_type][_idx];
    console.log("region:doSelectRegion:region=" + JSON.stringify(region));
    var idxData = this.data.regionIndex;
    if (idxData[_type] == _idx) {
      return;
    }
    idxData[_type] = _idx;
    this.setData({
      regionIndex: idxData,
    });
    if (_type < this.data.maxDataType) {
      this.loadRegion(_type + 1, region.region_id);
    }
  },
  doFinished:function(){
    var region = {};
    region.province = this.data.regionData[1][this.data.regionIndex[1]];
    region.city = this.data.regionData[2][this.data.regionIndex[2]];
    region.district = this.data.regionData[3][this.data.regionIndex[3]];
    my.L("selected_region",region);
    wx.navigateBack({
      delta:-1
    })
  },
  onShareAppMessage: app.share,

})